﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Configuration;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;

namespace WindowsFormsApplication1
{
    public partial class EnviromentChooser : Form
    {
        private const string EnviromentsAppSettingsName = "Enviroments";
        private const string HostFileFullNameSettingsName = "HostFileFullName";
        public EnviromentChooser()
        {
            InitializeComponent();
            lblMessage.Visible = false;
            PopulateEnvironments();
        }

        private void PopulateEnvironments()
        {
            string environmentsKeyValue = ConfigurationSettings.AppSettings[EnviromentsAppSettingsName].ToString();
            string[] environments = environmentsKeyValue.Split(';');
            for (int i = 0; i < environments.Length; i++)
            {
                string environment = environments[i];
                if (environment == null ||  environment.Equals(string.Empty))
                    continue;
                cmbEnvironment.Items.Add(environment);
            }

            if (cmbEnvironment.Items.Count > 0)
                cmbEnvironment.SelectedIndex = 0;
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            if (cmbEnvironment.SelectedIndex == -1)
                return;
            string hostFileName = ConfigurationSettings.AppSettings[HostFileFullNameSettingsName].ToString();
            string lineContent = null;

            string environmentsKeyValue = ConfigurationSettings.AppSettings[EnviromentsAppSettingsName].ToString();
            string[] environmentsArray = environmentsKeyValue.Split(';');
            Dictionary<string, string> enviroments = new Dictionary<string, string>();
            foreach (string env in environmentsKeyValue.Split(';'))
            {
                if (env ==null || env.Equals(string.Empty))
                    continue;

                enviroments.Add(env.ToLower(), env.ToLower());

            }

            Regex regex = new Regex("^#");
            Regex hostEntriesPattern = new Regex(@"^[0-9][0-9][0-9].");
            string choosenEnviroment = cmbEnvironment.SelectedItem.ToString().ToLower();
            StringBuilder hostEntriesBuilder = new System.Text.StringBuilder();
            bool unComment = false;
            string currentEnvironment = null;
            using (TextReader reader = new StreamReader(hostFileName))
            {
                lineContent = ReadLine(reader, hostEntriesBuilder);
                while (lineContent != null)
                {
                    lineContent = ReadLine(reader, hostEntriesBuilder, false);

                    if (lineContent != null)
                    {
                        if (regex.IsMatch(lineContent) && enviroments.ContainsKey(lineContent.Substring(1).ToLower()))
                        {
                            currentEnvironment = lineContent.Substring(1).ToLower();
                        }

                        if (currentEnvironment != null)
                        {
                            unComment = currentEnvironment == choosenEnviroment;

                            if (lineContent != null)
                            {

                                if (unComment && (regex.IsMatch(lineContent) && hostEntriesPattern.IsMatch(lineContent.Substring(1))))
                                {
                                    lineContent = lineContent.Substring(1);
                                }
                                else if (!unComment && hostEntriesPattern.IsMatch(lineContent))
                                {
                                    lineContent = "#" + lineContent;
                                }

                            }
                        }

                    }

                    hostEntriesBuilder.AppendLine(lineContent);
                }
                reader.Close();
            }

            using (FileStream fileStream = new FileStream(hostFileName, FileMode.Truncate, FileAccess.ReadWrite))
            {
                StreamWriter streamWriter = new StreamWriter(fileStream);
                streamWriter.Write(hostEntriesBuilder.ToString());
                streamWriter.Flush();
                streamWriter.Close();
                fileStream.Close();
            }

            lblMessage.Visible = true;
            lblMessage.Text = "Changed to: " + cmbEnvironment.SelectedItem.ToString();

        }

        private string ReadLine(TextReader reader, StringBuilder hostEntriesBuilder, bool append = true)
        {
            string lineContent = reader.ReadLine();

            if (lineContent != null)
                lineContent = lineContent.Trim();

            if (append)
                hostEntriesBuilder.AppendLine(lineContent);

            return lineContent;
        }

        private void UpdateEnviromentEntries(bool unComment, TextReader reader, StringBuilder hostEntriesBuilder, Dictionary<string, string> enviroments, Regex enviromentRegexPattern)
        {
            string lineContent = ReadLine(reader, hostEntriesBuilder, false);
            Regex hostEntriesPattern1 = new Regex("^#");
            Regex hostEntriesPattern2 = new Regex(@"^[0-9][0-9][0-9].");
            while (lineContent != null)
            {
                if (enviromentRegexPattern.IsMatch(lineContent))
                {
                    unComment = enviroments.ContainsKey(lineContent.Substring(1).ToLower());
                }
                if (lineContent != null)
                {
                    if (unComment && (hostEntriesPattern1.IsMatch(lineContent) && hostEntriesPattern2.IsMatch(lineContent.Substring(1))))
                    {
                        lineContent = lineContent.Substring(1);
                    }
                    else if (!unComment && hostEntriesPattern2.IsMatch(lineContent))
                    {
                        lineContent = "#" + lineContent;
                    }
                }

                hostEntriesBuilder.AppendLine(lineContent);

                lineContent = ReadLine(reader, hostEntriesBuilder, false);

            }
        }
    }
}


